﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Composite.Regions;
using Douban.Core.Menus;
using Douban.Core;
using Microsoft.Practices.Composite.Presentation.Commands;
using Douban.Modules.Friends.Views;
using Douban.Api;
using Douban.Modules.Friends.ViewModels;
using Microsoft.Practices.Unity;
using Douban.Api.User;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using Douban.Core.Settings;

namespace Douban.Modules.Friends
{
    public class FriendController
    {
        private DoubanService _doubanService;
        private IUnityContainer _container;
        private IRegionManager _regionManager;
        private IMenuManager _menuManager;
        private ISettingManager _settingManager;
        private IContactListViewModel _contactListViewModel;
        private IContactListViewModel _friendListViewModel;
        private UserDetail _currentUser;
        private DispatcherTimer _timer;
        private const double RefreshInterval = 2.0;

        public FriendController(
            DoubanService doubanService,
            IUnityContainer container, 
            IRegionManager regionManager, 
            IMenuManager menuManager,
            ISettingManager settingManager)
        {
            _container = container;
            _doubanService = doubanService;
            _regionManager = regionManager;
            _menuManager = menuManager;
            _settingManager = settingManager;
        }

        public void Run()
        {
            RegisterViewsWithRegion();
            RegisterMenus();
            SetUpdateTimer();
        }

        private void SetUpdateTimer()
        {
            _settingManager.Register("RefreshFrequency",
                (name, value) =>
                {
                    if (_timer != null) _timer.Stop();

                    _timer = new DispatcherTimer();
                    _timer.Interval = TimeSpan.FromMinutes((double)value);
                    _timer.Tick += _timer_Tick;

                    _timer.Start();
                });

            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMinutes(_settingManager.Settings.RefreshFrequency);
            _timer.Tick += _timer_Tick;

            _timer.Start();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            UpdateViewModels();
        }

        private void RegisterViewsWithRegion()
        {
            var userService = _doubanService.UserService;
            _currentUser = userService.GetCurrentUser();

            _contactListViewModel = _container.Resolve<IContactListViewModel>();
            _friendListViewModel = _container.Resolve<IContactListViewModel>();

            _regionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => _contactListViewModel.View);
            _regionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => _friendListViewModel.View);

            UpdateViewModels();
        }

        private void UpdateViewModels()
        {
            UpdateViewModel(_contactListViewModel, true);
            UpdateViewModel(_friendListViewModel, false);
        }

        private void UpdateViewModel(IContactListViewModel vm, bool getContacts)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
            {
                e.Result = GetContacts(_currentUser.Id, _doubanService.UserService, getContacts);
            };

            worker.RunWorkerCompleted += (sender, e) => 
            {
                vm.Contacts = (ObservableCollection<ContactListItemViewModel>)e.Result;
            };
            worker.RunWorkerAsync();
        }

        private ObservableCollection<ContactListItemViewModel> GetContacts(
            string userId, UserServiceProvider userService, bool getContacts)
        {
            ObservableCollection<ContactListItemViewModel> contactList = new ObservableCollection<ContactListItemViewModel>();
            var contacts = getContacts ? userService.GetContacts(userId) : userService.GetFriends(userId);
            if (contacts.Users == null)
                contacts.Users = new List<UserDetail>();

            foreach (var c in contacts.Users)
                contactList.Add(new ContactListItemViewModel(c));

            return contactList;
        }

        private void RegisterMenus()
        {
            IRegion region = _regionManager.Regions[RegionNames.MainRegion];

            MenuItem friendMenuItem = new MenuItem
            {
                Icon = "pack://application:,,,/Douban.Modules.Friends;Component/Images/talk.png",
                Name = "朋友",
                Command = new DelegateCommand<object>(
                    obj => region.Activate(_friendListViewModel.View),
                    obj => _friendListViewModel.View != null)
            };

            MenuItem contactMenuItem = new MenuItem
            {
                Icon = "pack://application:,,,/Douban.Modules.Friends;Component/Images/comment.png",
                Name = "关注的人",
                Command = new DelegateCommand<object>(
                    obj => region.Activate(_contactListViewModel.View),
                    obj => _contactListViewModel.View != null)
            };

            _menuManager.Add(friendMenuItem);
            _menuManager.Add(contactMenuItem);
        }
    }
}
